import express from 'express';
import { selectLatestArticles, selectHotArticles, selectLatestArticlesContent, selectHotArticlesContent, selectArticleById, getPrevArticle, getNextArticle } from '../../controllers/articles.js';
import { cleanArticleContent } from '../../util/util.js';
const router = express.Router();

// 接口5: 最新资讯 (/index/latest)，只返回5条
router.get('/latest', async (req, res) => {
    try {
        const articles = await selectLatestArticles();
        const cleanedArticles = articles.map(article => ({
            id: article.id,
            title: cleanArticleContent(article.title),
            intro: cleanArticleContent(article.content),
            cover: article.cover,
            category: article.type,
            read: article.read,
            comments: article.comments || 0,
            date: article.date
        }));
        // res.json()专门用于返回 JSON 格式的数据;res.send()可以返回任意类型的数据
        res.json({
            code: 200,
            message: '获取最新文章成功',
            data: cleanedArticles
        });
    } catch (error) {
        console.error('获取最新文章失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取最新文章失败',
            error: error.message
        });
    }
});

// 接口3: 热点图片 (/index/hotpic) - 返回5条
router.get('/hotpic', async (req, res) => {
    try {
        const articles = await selectLatestArticles();
        const limitedArticles = articles.slice(0, 5);
        const cleanedArticles = limitedArticles.map(article => ({
            id: article.id,
            cover: article.cover,
            title: cleanArticleContent(article.title)
        }));
        res.json({
            code: 200,
            message: '获取热点图片成功',
            data: cleanedArticles
        });
    } catch (error) {
        console.error('获取热点图片失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取热点图片失败',
            error: error.message
        });
    }
});

// 接口4: 文章热门排行 (/index/rank) - 返回7条
router.get('/rank', async (req, res) => {
    try {
        const articles = await selectHotArticles();
        const limitedArticles = articles.slice(0, 7);
        const cleanedArticles = limitedArticles.map(article => ({
            id: article.id,
            title: cleanArticleContent(article.title)
        }));
        res.json({
            code: 200,
            message: '获取文章排行成功',
            data: cleanedArticles
        });
    } catch (error) {
        console.error('获取文章排行失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取文章排行失败',
            error: error.message
        });
    }
});

// 接口7: 焦点关注 (/index/attention) - 返回7条文章内容截取
router.get('/attention', async (req, res) => {
    try {
        const articles = await selectHotArticles(7); 
        const cleanedArticles = articles.map(article => {
            let intro = '';
            let content = article.content || '';
            
            if (content.length > 0) {
                // 去除HTML标签
                content = content.replace(/<[^>]*>/g, ' ');
                // 去除HTML实体
                content = content.replace(/&[a-zA-Z0-9#]+;/g, ' ');
                // 去除多余空白字符
                content = content.replace(/\s+/g, ' ').trim();
                
                // 智能内容提取：跳过日期和短句
                let sentences = content.split(/[。！？.!?]/);
                let meaningfulContent = '';
                
                for (let sentence of sentences) {
                    sentence = sentence.trim();
                    // 跳过日期格式和太短的句子
                    if (sentence.length >= 15 && 
                        !/^\d+年\d+月\d+日/.test(sentence) && 
                        !/^\d+月\d+日/.test(sentence) &&
                        !/^[\d\s,，、]*$/.test(sentence) &&
                        !/^收听文本/.test(sentence) &&
                        !/^\d+:\d+\/\d+:\d+/.test(sentence)) {
                        meaningfulContent += sentence + '。';
                        if (meaningfulContent.length >= 200) {
                            break;
                        }
                    }
                }
                
                // 如果智能提取失败，使用原始内容但跳过开头
                if (meaningfulContent.length < 80) {
                    // 查找第一个句号后的内容
                    let firstPeriodIndex = content.indexOf('。');
                    if (firstPeriodIndex > 0 && firstPeriodIndex < content.length - 30) {
                        intro = content.substring(firstPeriodIndex + 1).trim();
                    } else {
                        // 跳过前50个字符
                        intro = content.length > 50 ? content.substring(50) : content;
                    }
                } else {
                    intro = meaningfulContent;
                }
                
                // 确保intro有最小长度
                if (intro.length < 50 && content.length > intro.length) {
                    intro = content.substring(0, 200);
                }
                
                // 截取最大280个字符
                if (intro.length > 280) {
                    intro = intro.substring(0, 280) + '...';
                }
            }
            
            // 如果intro仍然太短，使用标题作为备用
            if (!intro || intro.length < 30) {
                intro = article.title ? `${article.title} - 精彩内容请点击查看` : '文章内容摘要暂无...';
            }
            
            return {
                intro: intro
            };
        });
        
        res.json({
            code: 200,
            message: '获取焦点关注成功',
            data: cleanedArticles
        });
    } catch (error) {
        console.error('获取焦点关注失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取焦点关注失败',
            error: error.message
        });
    }
});

// 接口8: 文章详细内容 (/index/article) 
router.get('/article', async (req, res) => {
    try {
        let id = req.query?.id ?? "";
        if (id == "") {
            return res.json({
                code: 400,
                message: '参数有误'
            });
        }
        
        const articles = await selectArticleById(id);
        if (articles.length === 0) {
            return res.status(404).json({
                code: 404,
                message: '文章不存在'
            });
        }
        
        const article = articles[0];
        
        // 并行获取上一篇和下一篇文章
        const [prevArticles, nextArticles] = await Promise.all([
            getPrevArticle(id),
            getNextArticle(id)
        ]);
        
        const prev = prevArticles.length > 0 ? {
            id: prevArticles[0].id,
            title: prevArticles[0].title
        } : {};
        
        const next = nextArticles.length > 0 ? {
            id: nextArticles[0].id,
            title: nextArticles[0].title
        } : {};
        
        // 按照API文档格式返回
        res.json({
            code: 200,
            message: '获取文章详情成功',
            data: {
                title: cleanArticleContent(article.title),
                author: article.author,
                type: article.type,
                date: article.date,
                read: article.read,
                comments: article.comments || 0,
                content: article.content, 
                prev: prev,
                next: next
            }
        });
    } catch (error) {
        console.error('获取文章详情失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取文章详情失败',
            error: error.message
        });
    }
});

export default router;
